import dotenv from 'dotenv'
import path from 'path'

class ConfigError extends Error {
  constructor(message) {
    super(`[Config Error] ${message}`)
    this.name = 'ConfigError'
  }
}

// 类型验证器
const validators = {
  string: (val) => typeof val === 'string',
  number: (val) => !isNaN(Number(val)),
  boolean: (val) => val === 'true' || val === 'false'
}

// 必需字段检查
function checkRequired(env, required = []) {
  const missing = required.filter(key => !env[key])
  if (missing.length) {
    throw new ConfigError(`Missing required env variables: ${missing.join(', ')}`)
  }
}

// 加载环境变量
const env = process.env.NODE_ENV || 'development'
const envPath = path.resolve(process.cwd(), `.env.${env}`)

dotenv.config({ path: envPath })

// 验证必需字段
checkRequired(process.env, ['APP_NAME', 'API_BASE_URL'])

export default {
  // 应用配置
  app: {
    name: process.env.APP_NAME,
    version: process.env.APP_VERSION || '1.0.0'
  },

  // API配置
  api: {
    baseUrl: process.env.API_BASE_URL,
    timeout: parseInt(process.env.API_TIMEOUT) || 10000,
    prefix: process.env.API_PREFIX || '/api'
  },

  // 功能开关
  features: {
    payment: process.env.FEATURE_PAYMENT === 'true',
    coupon: process.env.FEATURE_COUPON === 'true',
    membership: process.env.FEATURE_MEMBERSHIP === 'true'
  },

  // 调试模式
  debug: process.env.DEBUG === 'true'
}